#include "StdAfx.h"
#include "AmpADSR.h"


CAmpADSR::CAmpADSR(void)
{
	mSustainVolume = 0.9;
}


CAmpADSR::~CAmpADSR(void)
{
}

void CAmpADSR::Start( void )
{
	mTime = 0.0;
	double lBps = 1 / ( GetBPM() / 60 );
	mDecay = mDuration * 0.05 * lBps;
	mSustain = mDuration * 0.1 * lBps;
	mRelease =mDuration * 0.15 * lBps;
	mState = Attack;
}

bool CAmpADSR::Generate( void )
{
	double lRamp = 0;
	double lBps = 1 / ( GetBPM() / 60 );
	double lActual = mDuration * lBps;

	if ( mTime < mDecay )
		lRamp = mTime / mDecay;
	// Decay
	else if( mTime < mSustain )
	{
		lRamp = ( (1 - mSustainVolume) * ( 1 - ( mTime - mDecay ) / ( mSustain - mDecay ))) + mSustainVolume ;
		mState = Decay;
	}
	// Sustain
	else if( mTime < mRelease )
	{
		lRamp = mSustainVolume;
		mState = Sustain;
	}
	// Release
	else if( mTime <  lActual )
	{
		lRamp = ( mSustainVolume * ( lActual - mTime ) ) / ( lActual - mRelease );
		mState = Release;
	}
	else if ( mTime > lActual )
	{
		lRamp = 0;
		return false;
	}
	
	mFrame[0] = mSource->Frame(0) * lRamp;
	mFrame[1] = mFrame[0];
	mTime += GetSamplePeriod();

	return true;
}